<template>
  <view class="detail-view">
    <!-- 头部信息 -->
    <view class="detail-header-section">
      <view class="header-row">
        <text class="header-label">单据号:</text>
        <text class="header-value">{{ arrivalMaster.cCode }}</text>
      </view>
      <view class="header-row">
        <text class="header-label">供应商:</text>
        <text class="header-value">{{ arrivalMaster.vName }}</text>
      </view>
      <view class="header-row">
        <text class="header-label">制单人:</text>
        <text class="header-value">{{ arrivalMaster.makeMan }}</text>
      </view>
      <view class="header-row">
        <text class="header-label">到货日期:</text>
        <text class="header-value">{{ arrivalMaster.dDate }}</text>
      </view>
      <view class="header-row">
        <text class="header-label">状态:</text>
        <text class="header-value">{{ arrivalMaster.status || '开立' }}</text>
      </view>
    </view>

    <!-- 明细列表 -->
    <view class="detail-list">
      <u-list @scrolltolower="scrollTolower" @scrollWithAnimation="true" :key="listKey">
        <u-list-item v-for="(item, index) in items" :key="index" class="detail-item">
          <view class="detail-card" @click="showDetailDialog(item)">
            <view class="detail-header">
              <text class="material-code">{{ item.cInvCode }}</text>
            </view>

            <view class="detail-content">
              <view class="detail-row">
                <text class="detail-label">物料名称:</text>
                <text class="detail-value">{{ item.invName }}</text>
              </view>

              <view class="detail-row">
                <text class="detail-label">采购订单:</text>
                <text class="detail-value">{{ item.cPOID }}</text>
              </view>

              <u-row>
                <u-col span="6">
                  <view class="detail-row">
                    <text class="detail-label">订单数量:</text>
                    <text class="detail-value">{{ item.podQty }}</text>
                  </view>
                </u-col>
                <u-col span="6">
                  <view class="detail-row">
                    <text class="detail-label">累计到货:</text>
                    <text class="detail-value">{{ item.iReceivedQTY }}</text>
                  </view>
                </u-col>
              </u-row>

              <u-row>
                <u-col span="6">
                  <view class="detail-row">
                    <text class="detail-label">可收货数:</text>
                    <text class="detail-value">{{ item.availableQty }}</text>
                  </view>
                </u-col>
                <u-col span="6">
                  <view class="detail-row">
                    <text class="detail-label">到货数量:</text>
                    <text class="detail-value">{{ item.revQty}}</text>
                  </view>
                </u-col>
              </u-row>

              <u-row>
                <u-col span="6">
                  <view class="detail-row">
                    <text class="detail-label">单位:</text>
                    <text class="detail-value">{{ item.cComUnitName }}</text>
                  </view>
                </u-col>
                <u-col span="6">
                  <view class="detail-row">
                    <text class="detail-label">仓库:</text>
                    <text class="detail-value">{{ item.whCode }}</text>
                  </view>
                </u-col>
              </u-row>

              <view v-if="item.isBatch === '1'" class="detail-row batch-row">
                <text class="detail-label">批次:</text>
                <text class="detail-value">{{ item.cBatch || '' }}</text>
              </view>
            </view>
          </view>
        </u-list-item>
      </u-list>
    </view>

    <u-loading-icon :show="loading" text="加载中" textSize="18"></u-loading-icon>

    <!-- 明细弹窗 -->
    <detail-dialog
      :show="showDialog"
      :item="currentItem"
      @closeDialog="closeDialog"
      @saveDialog="saveDialog"
      @deleteItem="deleteItem"
    />

    <!-- 底部按钮 -->
    <view class="fixed-bottom">
      <u-button @click="closeDetail" class="close-btn">关闭</u-button>
      <u-button
        v-if="!arrivalMaster.status || arrivalMaster.status === '开立'"
        @click="auditArrival"
        class="audit-btn"
        type="success"
      >
        审核
      </u-button>
    </view>
  </view>
</template>

<script>
import DetailDialog from './DetailDialog.vue';
import { deleteArrivalItem, updateArrivalItem, auditArrivalVouch } from '@/api/work/wareHourse/arrival.js'
import user from "@/store/modules/user";

export default {
  name: "ArrivalDetail",
  components: {
    DetailDialog
  },
  props: {
    arrivalMaster: {
      type: Object,
      default: () => ({})
    },
    items: {
      type: Array,
      default: () => []
    },
    listKey: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showDialog: false,
      currentItem: null
    };
  },
  methods: {
    showDetailDialog(item) {
      this.currentItem = {...item}; // 创建副本避免直接修改原数据
      this.currentItem.iQuantity = item.revQty;
      this.showDialog = true;
    },

    closeDetail() {
      this.$emit('closeDetail');
    },

    scrollTolower() {
      this.$emit('scrollToLower');
    },

    closeDialog() {
      this.showDialog = false;
      this.currentItem = null;
    },

    saveDialog() {
      // 保存修改的数据
      if (!this.currentItem.autoId) {
        this.$modal.showToast('无效的明细项');
        return;
      }

      const revQty = parseFloat(this.currentItem.revQty);
      const availableQty = parseFloat(this.currentItem.availableQty);
      const iQuantity = parseFloat(this.currentItem.iQuantity) || 0;

      // 验证到货数量必须大于0
      if (revQty <= 0) {
        this.$modal.showToast('到货数量必须大于0');
        return;
      }

      if (revQty === iQuantity) {
        this.$modal.showToast('到货数量未修改，不用保存');
        return;
      }

      // 验证修改时增加的幅度不能导致总到货数量超过可到货数量
      const increaseAmount = revQty - iQuantity;
      if (increaseAmount > 0 && increaseAmount > availableQty) {
        this.$modal.showToast('增加后的总到货数量不能超过可收货数量');
        return;
      }

      updateArrivalItem(
          this.currentItem.autoId,
          this.currentItem.revQty,
          this.currentItem.whCode
      ).then(res => {
        if (res.code === 200) {
          this.$modal.showToast('保存成功');

          // 更新本地数据
          const index = this.items.findIndex(item => item.autoId === this.currentItem.autoId);
          if (index !== -1) {
            this.items[index].revQty = this.currentItem.revQty;
            this.items[index].whCode = this.currentItem.whCode;
            // 更新可收货数量
            this.items[index].availableQty = availableQty - increaseAmount;
            this.items[index].iQuantity = revQty;
            // 更新累计到货
            this.items[index].iReceivedQTY = this.items[index].iReceivedQTY + increaseAmount;
          }

          this.closeDialog();
        } else {
          this.$modal.showToast(res.msg || '保存失败');
        }
      })
    },

    deleteItem() {
      // 删除当前项
      if (!this.currentItem.autoId) {
        this.$modal.showToast('无效的明细项');
        return;
      }
      deleteArrivalItem(this.currentItem.autoId).then(res => {
        if (res.code === 200) {
          this.$modal.showToast('删除成功');

          // 从本地列表中移除
          const index = this.items.findIndex(item => item.autoId === this.currentItem.autoId);
          if (index !== -1) {
            this.items.splice(index, 1);
          }

          this.closeDialog();
        } else {
          this.$modal.showToast(res.msg || '删除失败');
        }
      });
    },

    // 审核到货单
    auditArrival() {
      // 确认审核
      this.$modal.confirm('确定要审核该到货单吗？').then(() => {
        const cverifier = user.state.nickName;
        auditArrivalVouch(this.arrivalMaster.cCode, cverifier).then(response => {
          if (response.code === 200) {
            this.$modal.showToast('审核成功');
            // 更新状态
            this.arrivalMaster.status = '已审核';
            // 通知父组件刷新列表
            this.$emit('refreshList');
          } else {
            this.$modal.showToast('审核失败: ' + (response.msg || ''));
          }
        }).catch(err => {
          this.$modal.showToast('审核失败: ' + err);
        });
      }).catch(() => {
        // 用户取消审核
      });
    }
  }
};
</script>

<style scoped>
.detail-view {
  padding-bottom: 120rpx;
}

.detail-header-section {
  background: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.header-row {
  display: flex;
  margin-bottom: 12rpx;
}

.header-label {
  width: 160rpx;
  font-size: 26rpx;
  color: #666;
  font-weight: bold;
}

.header-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
}

.detail-item {
  margin-bottom: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  padding: 24rpx;
}

.detail-header {
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 16rpx;
}

.material-code {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.detail-row {
  display: flex;
  margin-bottom: 12rpx;
}

.detail-label {
  width: 160rpx;
  font-size: 26rpx;
  color: #666;
}

.detail-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
}

.batch-row {
  margin-top: 10rpx;
}

/* 底部按钮样式 */
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  text-align: center;
  background-color: #fff;
  z-index: 999;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
}

.close-btn {
  flex: 1;
  border-radius: 50rpx;
  height: 80rpx;
  background-color: #f5f5f5;
  color: #333;
  margin-right: 10rpx;
}

.audit-btn {
  flex: 1;
  border-radius: 50rpx;
  height: 80rpx;
  margin-left: 10rpx;
}
</style>
